﻿using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using PhysicalExamination5.Service;

namespace PhysicalExamination5.WebApi.Utility.Filters
{
    public class CustomAsyncExceptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(CustomActionFilterAttribute));
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public CustomAsyncExceptionFilterAttribute()
        {
        }

        /// <summary>
        /// 发生异常后就在这里处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            //在这里就应该处理异常
            if (context.ExceptionHandled == false) //如果没有被处理
            {
                context.Result = new JsonResult(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = context.Exception.Message
                });
                log.Error("错误信息:" + context.Exception.Message);
                //就在这里处理
                context.ExceptionHandled = true;//异常已经被处理过了；
            }

            await Task.CompletedTask;
        }
    }
}
